import axios from 'axios';
import type { AxiosRequestConfig, AxiosResponse } from 'axios';
import { Message, Modal } from '@arco-design/web-vue';
import { useUserStore, useStation } from '@/store';
import { getToken } from '@/utils/auth';

export interface HttpResponse<T = unknown> {
    status: number;
    msg: string;
    message: string;
    code: number;
    data: T;
    result: T;
}

if (import.meta.env.VITE_API_BASE_URL) {
    axios.defaults.baseURL = import.meta.env.VITE_API_BASE_URL;
}

axios.interceptors.request.use(
    (config: AxiosRequestConfig) => {
        // let each request carry token
        // this example using the JWT token
        // Authorization is a custom headers key
        // please modify it according to the actual situation
        const token = getToken();
        if (token) {
            if (!config.headers) {
                config.headers = {};
            }
            const userStation = useStation();
            config.headers.Authorization = `Bearer ${token}`;
            const { stationId } = userStation;
            config.headers.stationId = stationId;
            config.headers.lang =
                localStorage.getItem('enric-locale') || 'zh-CN';
            if (config.method === 'get') {
                config.params = {
                    ...config.params,
                    lang: localStorage.getItem('enric-locale') || 'zh-CN',
                    stationId,
                };
            } else if (config.method === 'post') {
                config.data = {
                    ...config.data,
                    lang: localStorage.getItem('enric-locale') || 'en-US',
                    stationId,
                };
            }
        }
        return config;
    },
    (error) => {
        // do something
        return Promise.reject(error);
    }
);
// add response interceptors
axios.interceptors.response.use(
    (response: AxiosResponse<HttpResponse>) => {
        const res = response.data;
        if ([401].includes(res.status)) {
            Modal.error({
                title: '提示',
                content: res.msg || res.message,
                okText: '确定',
                maskClosable: false,
                closable: false,
                escToClose: false,
                async onOk() {
                    const userStore = useUserStore();
                    await userStore.logoutCallBack();
                    window.location.reload();
                },
            });
            return Promise.reject(new Error(res.message || 'Error'));
        }
        // if the custom code is not 20000, it is judged as an error.
        if (res.status !== 200) {
            Message.error({
                content: res.message || 'Error',
                duration: 5 * 1000,
            });
            return Promise.reject(new Error(res.message || 'Error'));
        }
        return res;
    },
    (error) => {
        Message.error({
            content: error.msg || error.message || 'Request Error',
            duration: 5 * 1000,
        });
        return Promise.reject(error);
    }
);
